from threading import Thread
from MsgProcess import MsgProcess, MsgType
import time

import ctypes
dll = ctypes.cdll.LoadLibrary("plugin/Temperature_and_humidity/dht11.so")
class StructPointer(ctypes.Structure):
    _fields_ = [
    ("temperature",ctypes.c_long),
    ("humidity",ctypes.c_long),
    ("temperature_decimal",ctypes.c_long),
    ("humidity_decimal",ctypes.c_long),
    ]


class Temperature_and_humidity(MsgProcess):

    def Start(self, message):

        self.dhtdata="没有数据"
        self.mythread=Thread( target=self.dht )
        self.mythread.start()
        

    def dht(self):

        while 1:
            
            dll.main.restype = ctypes.POINTER(StructPointer)
            p = dll.main(3)#wiring编码gpio
            self.dhtdata = "温度{0}.{1}摄氏度,湿度{2}.{3}%".format(p.contents.temperature,p.contents.temperature_decimal,p.contents.humidity,p.contents.humidity_decimal)


    #执行入口
    def Text(self, message):
        Data = message['Data']
        #微信进入事件
        if type(Data) is dict  and 'initstate' in dict(Data).keys():
            if Data['initstate'] == 'onLoad':
                data = {'action':"Temperature_and_humidity","Temperature_and_humidity":self.dhtdata , "Temperature_and_humidity_Time":time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) }                 
                self.send(MsgType.Text, Receiver='MqttProxy', Data=data)
            return 

        
        data = {'action':"Temperature_and_humidity","Temperature_and_humidity":self.dhtdata , "Temperature_and_humidity_Time":time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) }                 
        self.send(MsgType.Text, Receiver='MqttProxy', Data=data)
        self.say(self.dhtdata)